<template>
  <div class="cmt-comtainer">
    <h3>发表评论</h3>
    <hr>
    <textarea placeholder="请输入需要吐槽的内容（最多120字）" maxlength="=120" v-model="comment"></textarea>

    <mt-button type="primary" size="large" @click="getComments">发表评论</mt-button>
    <div class="cmt-list">
      <div class="cmt-item" v-for="(item,i) in list" :key="item.id">
        <div
          class="cmt-title"
        >第{{i+1}}楼&nbsp;&nbsp;用户：{{item.id}}&nbsp;&nbsp;&nbsp;发表时间：{{item.time | dateFormat}}</div>
        <div class="cmt-body">
          {{item.comment}}
        </div>
      </div>
    </div>

    <mt-button type="danger" size="large" plain>加载更多</mt-button>
  </div>
</template>
<script>
import {Toast} from 'mint-ui';
export default {
  data() {
    return {
      comment: "",
      list: [{}]
    };
  },
  created() {
    this.loadComments();
  },
  methods: {
    getComments() {
      var comment = {
        id: Date.now(),
        user: "",
        comment: this.comment,
        time: new Date()
      };
        if(comment.comment.trim().length>0){
            // 从localhost获取所有的数据
            var list = JSON.parse(localStorage.getItem("cmts") || "[]");
            list.unshift(comment);
            // 保留最新评论
            localStorage.setItem("cmts", JSON.stringify(list));
            this.comment = "";
        }else{
             Toast("请输入评论内容!");
        }
     
      this.loadComments();
    },
    loadComments() {
      var list = JSON.parse(localStorage.getItem("cmts") || "[]");
      this.list = list;
    }
  }
};
</script>
<style lang="scss" scoped>
.cmt-comtainer {
  h3 {
    font-size: 18px;
  }
  textarea {
    font-size: 14px;
    height: 85px;
    margin: 0;
  }
  .cmt-list {
    margin-top: 10px;
    .cmt-item {
      font-size: 13px;
      .cmt-title {
        line-height: 30px;
        background-color: #eee;
      }
      .cmt-body {
        line-height: 35px;
        text-indent: 2rem;
        font-size: 15px;
      }
    }
  }
}
</style>
